package struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.action.form.Action;
import struts.action.form.ActionForm;
import struts.action.form.FullForm;
import struts.util.XMLBean;


/**
 * Servlet implementation class ActionServlet
 */
@WebServlet("/ActionServlet")
public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ActionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    private String getPath(String servletPath) {
    	return servletPath.split("\\.")[0];
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取请求头的请求路径
		String path=this.getPath(request.getServletPath());
		Map<String,XMLBean> map=(Map<String,XMLBean>)this.getServletContext().getAttribute("struts");
		XMLBean xml=map.get(path);
		String formClass=xml.getFormClass();
		ActionForm form=FullForm.full(formClass,request);
		String actionType=xml.getActionType();
		String actinClass=xml.getActionType();
		Action action=null;
		String url="";
		try {
			Class clazz=Class.forName(actionType);
			action =(Action) clazz.newInstance();
			url=action.excute(request,response,form, xml.getForwardMap());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
//		//获得了转发器对象
		RequestDispatcher dis=request.getRequestDispatcher(url);
		dis.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
